//
//  ViewController.m
//  07-nsurlsession04-大文件下载的进度
//
//  Created by J on 16/2/26.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
 
    [self downLoad];
}

- (void)downLoad{
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];//获得
//
    NSURLSessionDownloadTask* task = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Media/H264_test1_Talkinghead_mp4_480x360.mp4"]]];
//
//    [task resume];
//


}

#pragma mark --NSURLSessionDownloadDelegate



//恢复下载调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    NSLog(@"didResumeAtOffset");

}


//没当写入数据到临时文件时,就会调用一次 多次调用
//totalBytesExpectedToWrite总大小
//totalBytesWritten已经写入大小
//bytesWritten这次写入多少
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    NSLog(@"%f",1.0*totalBytesWritten/totalBytesExpectedToWrite);//要让其中一个变为float计算出的结果才是float
    //    NSLog(@"%f",totalBytesWritten/(totalBytesExpectedToWrite*1.0));

    
}

//下载完毕调用一次
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSLog(@"didFinishDownloadingToURL");

    //将来要存放的文件真实路径
    NSString* file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];//服务器给的文件名 104527c7dbbb3d3jjkckcb.jpg
    
    
    UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
    NSLog(@"%@",image);
    
    UIImageView* imageView = [[UIImageView alloc]initWithImage:image];
    dispatch_async(dispatch_get_main_queue(), ^{//下载会被放到分线程中
        imageView.center = self.view.center;
        //           imageView.backgroundColor = [UIColor orangeColor];
        NSLog(@"%@",imageView.image);
        [self.view addSubview:imageView];
        
    });
    NSFileManager* manager = [NSFileManager defaultManager];
    [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    
    
}


//任务完毕
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    
    
}


@end
